<template>
  <el-dialog
    :title="'上传附件'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
      <el-form-item label="附件" prop="file">
        <el-form-item label="上传附件">
              <el-upload
                :file-list="fileListArr"  
                action="http://localhost:8080/renren-fast/generator/projectfile/save"
                ref="scfj"
                accept=".jpg, .png, .jpeg, .gif, .bmp, .xls, .xlsx, .doc, .docx, .rar, .zip"
                :before-upload="beforeUploadFj"
                :on-exceed="handleExceedFj"
                :on-remove="handleRemoveFj"
                multiple
                :limit="10"
                :auto-upload="false"
                :on-change="onChangeFj"
              >
                <el-button slot="trigger" size="small" type="primary"
                  >选取文件</el-button
                >
                <el-button
                  style="margin-left: 10px;"
                  size="small"
                  type="success"
                  @click="uploadFj"
                  >上传附件</el-button
                >
              </el-upload>
            </el-form-item>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">返回</el-button>
      <!--<el-button type="primary" @click="dataFormSubmit()">确定</el-button>-->
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        visible: false,
        fileListArr: [],
        dataForm: {
          id: 0,
          fileOriginName: '',
          fileStorageName: ''
        },
        dataRule: {
          fileOriginName: [
            { required: true, message: '文件原名不能为空', trigger: 'blur' }
          ],
          fileStorageName: [
            { required: true, message: '文件存储名不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/generator/projectfile/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.fileOriginName = data.projectFile.fileOriginName
                this.dataForm.fileStorageName = data.projectFile.fileStorageName
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/generator/projectfile/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'fileOriginName': this.dataForm.fileOriginName,
                'fileStorageName': this.dataForm.fileStorageName
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      beforeUploadFj(file) {
        let zhzxFile = file.name.substring(file.name.lastIndexOf(".") + 1);
        const extension = zhzxFile === "jpg";
        const extension2 = zhzxFile === "jpeg";
        const extension3 = zhzxFile === "png";
        const extension4 = zhzxFile === "bmp";
        const extension5 = zhzxFile === "gif";
        const extension6 = zhzxFile === "xls";
        const extension7 = zhzxFile === "xlsx";
        const extension8 = zhzxFile === "doc";
        const extension9 = zhzxFile === "docx";
        const extension10 = zhzxFile === "zip";
        const extension11 = zhzxFile === "rar";

        // const isLt2M = file.size / 1024 / 1024 < 10   根据需求是否需要对上传文件大小进行限制
        if (
          !extension &&
          !extension2 &&
          !extension3 &&
          !extension4 &&
          !extension5 &&
          !extension6 &&
          !extension7 &&
          !extension8 &&
          !extension9 &&
          !extension10 &&
          !extension11
        ) {
          this.$message({
            message: "上传文件只能是 jpg、jpeg、png、bmp、gif、xls、xlsx、doc、docx、zip、rar格式!",
            type: "warning",
          });
        }
        // if(!isLt2M) {
        //     this.$message({
        //         message: '上传文件大小不能超过 10MB!',
        //         type: 'warning'
        //     });
        // }
        // return extension || extension2 && isLt2M
        return extension || extension2 || extension3 || extension4 || extension5  
        || extension6 || extension7 || extension8 || extension9 || extension10 || extension11;
      },



      //对上传文件超过个数进行限制
      handleExceedFj(files, fileList) {
        this.$message.warning(
          `当前限制选择 10 个文件，本次选择了 files.length个文件，共选择了{
            files.length + fileList.length
          } 个文件`
        );
      },
  
      //删除事件，需要根据具体业务分析，即删除时候从数组中去除选中的文件
      handleRemoveFj(file, fileList) {
        console.log(file.fileList)
        this.fileListArr = fileList;
        //let delArr = this.saveScfjArr.filter((item) => {
        // return item != file.name;
      //});

        //this.saveScfjArr = delArr;

        //this.gwModleObj.scfj = this.saveScfjArr;
      },
  
      //选择文件时候触发  需根据需求具体分析
      onChangeFj(file, fileList) {
        console.log(file.fileList)
        this.fileListArr = fileList;
        //this.gwModleObj.scfj = fileList;
        //this.$refs.gwModleObj.validateField("scfj");
        //this.saveSuccessId = 1;
      },

      //上传接口，进行上传
      uploadFj(value) {
        console.log('提交文件，文件列表为：')
        console.log(this.fileListArr)
        
        this.$refs.scfj.submit();
        let formData = new FormData();
        //所需参数
        this.fileListArr.forEach((item) => {
          formData.append("files", item.raw);
        });
        let obj = {
          id: this.dataForm.id
        }
        obj.id = this.dataForm.id
        console.log('obj为：')
        console.log(obj)
        //...  需要传入的参数
        formData.append('obj', JSON.stringify(obj))
        console.log('formData:')
        console.log(formData)
        //接口
        this.$http({
            url: this.$http.adornUrl(`/generator/projectfile/save`),
            method: 'post',
            data: formData
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
      }
    }
  }
</script>
